﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ZYB.Security
{
    public static class Security
    {
        /// <summary>
        /// 对字符串进行加密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string Encrypt(string str)
        {
            Console.WriteLine("加密前的消息体:");
            Console.WriteLine(str);
            var md5Str = MD5Tools.ToMD5String(str) + str;
            Console.WriteLine("加密后的消息体:");
            Console.WriteLine(md5Str);
            var b1 = Encoding.UTF8.GetBytes(str);
            Console.WriteLine("DES加密前的byte:");
            PrintBytes(b1);
            var b = DESTools.Encrypt(b1);
            Console.WriteLine("DES后的字节数组:");
            PrintBytes(b);
            var body = Base64Tools.Encode(b);
            Console.WriteLine("Base64后的字符串:");
            Console.WriteLine(body);
            return body;

        }
        /// <summary>
        /// 对字符串解密
        /// </summary>
        /// <param name="strbody"></param>
        /// <returns></returns>
        public static string Decrypt(string strbody)
        {
            Console.WriteLine("对方传来的消息源串:");
            Console.WriteLine(strbody);
            var b = Base64Tools.Decode(strbody);
            Console.WriteLine("BASE64解码之后的结果:");
            Security.PrintBytes(b);
            var b1 = DESTools.Decrypt(b);
            Console.WriteLine("DES解密后的byte[]");
            Security.PrintBytes(b1);
            var md5body = Encoding.UTF8.GetString(b1);
            Console.WriteLine("DES解密后的结果");
            Console.WriteLine(md5body);
            if (md5body.Length < 32)
            {
                Console.WriteLine("错误！消息体长度小于数字签名长度!");
                return string.Empty;
            }
            //var md5Client = md5body.Substring(0, 32);
            //Console.WriteLine($"对放传过来的数字签名:{md5Client}");
            //var body = md5body.Substring(32);
            //Console.WriteLine($"对方传来的消息体:{body}");
            //var md5Server = MD5Tools.ToMD5String(body);
            //Console.WriteLine($"我方对传来消息的数字签名:{md5Server}");
            //if (!md5Client.Equals(md5Server, StringComparison.OrdinalIgnoreCase))
            //{
            //    Console.WriteLine("数字签名不匹配!");
            //    return false;
            //}
            Console.WriteLine($"消息内容:{md5body}");
            return md5body;
        }
        public static void PrintBytes(byte[] b)
        {
            var sb = new StringBuilder();
            for (var i = 0; i < b.Length; i++)
            {
                sb.Append("[" + b[i] + "],");
                if (i % 15 == 0)
                {
                    sb.Append("\n");
                }
            }
            Console.WriteLine(sb.ToString());
        }
    }
}
